import wsgiref.handlers
import uuid
import cgi
import os
import xmlutils

from xml.etree.ElementTree import Element, ElementTree
from formencode import validators

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import model

class List(webapp.RequestHandler):
  def get(self):

    recordings = db.GqlQuery("SELECT * FROM Recording ORDER BY created DESC")
    artists = db.GqlQuery("SELECT * FROM Artist ORDER BY name")

    template_values = {'recordings' : recordings, 'artists' : artists}

    path = os.path.join(os.path.dirname(__file__), 'templates/recording_list.html')
    self.response.out.write(template.render(path, template_values))


class Add(webapp.RequestHandler):

  def post(self):

    # Determine the properties of the recording entity
    recording_title = self.request.get('title')
    recording_uuid = str(uuid.uuid4())
    artist_uuid = self.request.get('artist')
  
    # Make sure recording_title is not empty
    validators.NotEmpty().to_python(recording_title)

    # Retrieve the recording artist from the Datastore
    artists = db.GqlQuery("SELECT * FROM Artist WHERE uuid = :1", artist_uuid)
    artist = artists.get()    

    # Create a new recording entity and save it in the Datastore
    recording = model.Recording(title=recording_title, uuid=recording_uuid)
    recording.year = int(self.request.get('year'))
    recording.type = self.request.get('type')
    recording.description = self.request.get('description')
    recording.cover = db.Blob(self.request.get('cover'))
    recording.artist = artist.key()
    recording.put()

    # Display the newly created artist entity
    self.redirect('/recording/view?uuid=' + recording.uuid)


class Image(webapp.RequestHandler):
  def get(self):
    uuid = self.request.get('uuid')
    recordings = db.GqlQuery("SELECT * FROM Recording WHERE uuid = :1 LIMIT 1", uuid).fetch(1)
    recording = recordings[0]
    
    self.response.headers['Content-Type'] = 'image/jpg'
    
    if (recording.cover): 
      self.response.out.write(recording.cover)

class View(webapp.RequestHandler):
  def get(self):
    uuid = self.request.get('uuid')
    recordings = db.GqlQuery("SELECT * FROM Recording WHERE uuid = :1 LIMIT 1", uuid).fetch(1)
    recording = recordings[0]
    
    template_values = {'recording' : recording}

    path = os.path.join(os.path.dirname(__file__), 'templates/recording_view.html')
    self.response.out.write(template.render(path, template_values))


class New(webapp.RequestHandler):
  def get(self):

    artists = db.GqlQuery("SELECT * FROM Artist ORDER BY name")

    template_values = {'artists' : artists}

    path = os.path.join(os.path.dirname(__file__), 'templates/recording_new.html')
    self.response.out.write(template.render(path, template_values))


class Export(webapp.RequestHandler):
  def get(self):

    uuid = self.request.get('uuid')

    recordings = db.GqlQuery("SELECT * FROM Recording WHERE uuid = :1", uuid)
    recording = recordings.get()    

    recordingElement = Element('recording')
    recordingElement.attrib["uuid"] = recording.uuid

    titleElement = Element('title')
    titleElement.text = recording.title
    recordingElement.append(titleElement)

    yearElement = Element('year')
    yearElement.text = str(recording.year)
    recordingElement.append(yearElement)
    
    typeElement = Element('type')
    typeElement.text = recording.type
    recordingElement.append(typeElement)

    createdElement = Element('created')
    createdElement.text = str(recording.created)
    recordingElement.append(createdElement)

    artistElement = Element('artist')
    artistElement.text = recording.artist.name
    artistElement.attrib["uuid"] = recording.artist.uuid
    recordingElement.append(artistElement)

    descriptionElement = Element('description')
    descriptionElement.text = recording.description
    recordingElement.append(descriptionElement)

    coverElement = Element('cover')
    coverElement.text = 'TBD'
    recordingElement.append(coverElement)


    self.response.headers["Content-Type"] = "application/xml"
    self.response.headers["Content-disposition"] = "attachment; filename=recording.xml";
    
    xmlutils.indent(recordingElement)
    ElementTree(recordingElement).write(self.response.out)


def main():
  application = webapp.WSGIApplication( [
    ('/recording/list', List), 
    ('/recording/view', View), 
    ('/recording/add', Add), 
    ('/recording/export', Export),
    ('/recording/new', New),
    ('/recording/image', Image)  
  ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()

